package com.lintf.devdemo.utils;

import com.lintf.devdemo.entity.po.ISysFileInfo;
//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGEncodeParam;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/10/19-18:20
 * @ package_name:com.lintf.devdemo.utils
 * @ project_name:DevDemo
 * @ desc:文件处理工具类
 */
public class FileUtil {

    /**
     * 创建资源文件夹
     *
     * @param rootPath
     * @param uploadTime
     * @return
     */
    public static String getFolderPath(String rootPath, Date uploadTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dataPath = df.format(uploadTime);
        String folderPath = rootPath + dataPath + "/";
        File file = new File(folderPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return folderPath;
    }

    public static ISysFileInfo ajaxUplod(MultipartFile file, String path) throws IOException {
        ISysFileInfo fileInfo = new ISysFileInfo();
        String oldfileName = file.getOriginalFilename();
        fileInfo.setFileName(oldfileName);
        fileInfo.setFileType(file.getContentType());
        String fileDateName = UUID.randomUUID().toString().replaceAll("-", "");
        int index = oldfileName.lastIndexOf(".");
        String fileName = "";
        if (index > 0) {
            String str = oldfileName.substring(index, oldfileName.length());
            fileName = fileDateName + str;
        } else {
            fileName = fileDateName + "." + file.getContentType().split("/")[1];
        }
        upload(file, path, fileName);
        fileInfo.setFileLocation(path + fileName);
        return fileInfo;
    }

    public static void upload(MultipartFile file, String path, String fileName) throws IOException {
        File fileDir = new File(path);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdir();
        }

        if (file != null) {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;

            try {
                if ("blob".equals(file.getOriginalFilename())) {
                    String pathTemp = path + fileName;
                    inputStream = file.getInputStream();
                    outputStream = new FileOutputStream(pathTemp);
                    byte[] temp = new byte[1024];
                    boolean var9 = true;

                    int size;
                    while ((size = inputStream.read(temp)) != -1) {
                        outputStream.write(temp, 0, size);
                    }
                } else {
                    File localFile = new File(path, fileName);
                    file.transferTo(localFile);
                }
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }

            }

        }
    }

    public static void compress(String filePath) throws Exception {
        File file = new File(filePath);
        if (file.exists() && file.isFile() && file.length() > 0L) {
            String type = filePath.substring(filePath.lastIndexOf(".") + 1);
            if ("jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) {
                Image srcFile = ImageIO.read(new File(filePath));
                int width = ((BufferedImage) srcFile).getWidth();
                int height = ((BufferedImage) srcFile).getHeight();
                BufferedImage tag = new BufferedImage(width, height, 1);
                tag.getGraphics().drawImage(srcFile, 0, 0, width, height, (ImageObserver) null);

//                JDK1.8起图片压缩写法
                ImageIO.write(tag,type,new ByteArrayOutputStream());

//                JDK1.7图片压缩写法
//                FileOutputStream out = new FileOutputStream(filePath);
//                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//                JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
//                jep.setQuality(0.4F, true);
//                encoder.encode(tag, jep);
//                out.close();
            }
        }

    }

}
